# Select by similarity

This object selects examples based on similarity to the inputs. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs.

import CodeBlock from "@theme/CodeBlock";
import ExampleSimilarity from "@examples/prompts/semantic_similarity_example_selector.ts";

The fields of the examples object will be used as parameters to format the `examplePrompt` passed to the `FewShotPromptTemplate`.
Each example should therefore contain all required fields for the example prompt you are using.

import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx";

<IntegrationInstallTooltip></IntegrationInstallTooltip>

```bash npm2yarn
npm install @langchain/openai @langchain/community
```

<CodeBlock language="typescript">{ExampleSimilarity}</CodeBlock>

By default, each field in the examples object is concatenated together, embedded, and stored in the vectorstore for
later similarity search against user queries.

If you only want to embed specific keys
(e.g., you only want to search for examples that have a similar query to the one the user provides), you can pass an `inputKeys`
array in the final `options` parameter.

## Loading from an existing vectorstore

You can also use a pre-initialized vector store by passing an instance to the `SemanticSimilarityExampleSelector` constructor
directly, as shown below. You can also add more examples via the `addExample` method:

import ExampleSimilarityFromExisting from "@examples/prompts/semantic_similarity_example_selector_from_existing.ts";

<CodeBlock language="typescript">{ExampleSimilarityFromExisting}</CodeBlock>

## Metadata filtering

When adding examples, each field is available as metadata in the produced document. If you would like further control over your
search space, you can add extra fields to your examples and pass a `filter` parameter when initializing your selector:

import ExampleSimilarityMetadataFiltering from "@examples/prompts/semantic_similarity_example_selector_metadata_filtering.ts";

<CodeBlock language="typescript">
  {ExampleSimilarityMetadataFiltering}
</CodeBlock>

## Custom vectorstore retrievers

You can also pass a vectorstore retriever instead of a vectorstore. One way this could be useful is if you want to use retrieval
besides similarity search such as maximal marginal relevance:

import ExampleSimilarityCustomRetriever from "@examples/prompts/semantic_similarity_example_selector_custom_retriever.ts";

<CodeBlock language="typescript">{ExampleSimilarityCustomRetriever}</CodeBlock>
